package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.login.LoginUser;
import com.atguigu.lease.common.login.LoginUserHolder;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在这里添加认证逻辑，例如检查请求头中的令牌
        String token = request.getHeader("access-token");
        Claims claims = JwtUtil.parseToken(token);// 解析令牌，验证其有效性
        //解析后将信息添加到 LoginUserHolder 中
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginUserHolder.setLoginUser(new LoginUser(userId, username));
        return true;
    }

    private boolean isValidToken(String token) {
        // 实现令牌验证逻辑
        return true; // 这里仅为示例，实际应用中需要验证令牌的有效性
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理线程本地变量，防止内存泄漏
        LoginUserHolder.remove();
    }



}
